#!/usr/bin/env ruby

require 'socket'

class SimpleIrcBot

  def initialize(server, port, channel)
    @channel = channel
    @socket = TCPSocket.open(server, port)
    say "NICK Domian1978"
    say "USER Domian1978 0 * Domian1978"
    say "JOIN ##{@channel}"
    puts "#{1.chr}"
    say_to_chan "#{1.chr}ACTION is here to help#{1.chr}"
  end

  def say(msg)
    puts msg
    @socket.puts msg
  end

  def say_to_chan(msg)
    say "PRIVMSG ##{@channel} :#{msg}"
  end

  def run
    until @socket.eof? do
      msg = @socket.gets
      
      case msg.strip!
        when /^PING :(.+)$/i
            puts "1---> [ Server ping ]"
            say "PONG :#{$1}"
        when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]PING (.+)[\001]$/i
            puts "2---> [ CTCP PING from #{$1}!#{$2}@#{$3} ]"
            say "NOTICE #{$1} :\001PING #{$4}\001"
        when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]VERSION[\001]$/i
            puts "3---> [ CTCP VERSION from #{$1}!#{$2}@#{$3} ]"
            say "NOTICE #{$1} :\001VERSION Ruby-irc v0.042\001"
        when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+)\s:EVAL (.+)$/i
            puts "4---> [ EVAL #{$5} from #{$1}!#{$2}@#{$3} ]"
            say "PRIVMSG #{(($4==@nick)?$1:$4)} :#{$5}"
        when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s\#(.+?)\s\:(.+?)$/i # room message
            handle_room_message($5)
        when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+?)\s\:(.+?)$/i # private message
            handle_private_message($5)
        else
            puts "0---> #{msg}"            
      end
    end
  end  

  def handle_room_message(message)
    puts "Room Message:: Use log4r to log it---> #{message}"
  end

  def handle_private_message(message)
    puts "Private Message---> #{message}"
    exit 0 if message == "quit"

    output = %x("#{message}").split("\n")
    output.each { |l| say_to_chan l } if output
  end
  
  def quit
    say "PART ##{@channel} :Daisy, Daisy, give me your answer do"
    say 'QUIT'
  end
end

bot = SimpleIrcBot.new("irc.freenode.net", 6667, 'koalabottest')

trap("INT"){ bot.quit }

bot.run
